package leetcode;

import java.util.ArrayList;
import java.util.List;

public class Code6 {

    public static String convert(String s, int numRows) {
        if(numRows < 2){
            return s;
        }

        List<StringBuilder> allLines = new ArrayList<>();

        for(int i=0;i<numRows;i++){
            allLines.add(new StringBuilder());
        }

        int curRow = 0;
        int flag = 1;

        for (int i = 0; i < s.length(); i++) {
            allLines.get(curRow).append(s.charAt(i));
            curRow += flag;
            if(curRow == 0 || curRow == numRows-1){
                flag = -flag;
            }
        }
        StringBuilder result = new StringBuilder();
        for (StringBuilder sb :
                allLines) {
            result.append(sb.toString());
        }
        return result.toString();
    }

    public static String convert1(String s, int numRows) {
        if(numRows == 1){
            return s;
        }

        int length = s.length();
        char[] convert = new char[length];
        int convertIndex = 0;
        for(int i = 0;i< numRows;i++){
            int startIndex = i;
            boolean revert = false;
            while(startIndex < length){
                convert[convertIndex++] = s.charAt(startIndex);
                int nextIndex = startIndex;
                if(!revert){
                    nextIndex = startIndex + 2*(numRows - i -1);
                }else{
                    nextIndex = startIndex + 2 * i;
                }
                revert = !revert;
                if(nextIndex == startIndex){
                    convertIndex--;
                }else{
                    startIndex = nextIndex;
                }

            }
        }
        return new String(convert);
    }

    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        System.out.println(convert(s,3));
    }
}
